package com.yunxin.admin.system.infra.persistence.repository;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunxin.admin.system.domain.model.user.UserMerchantRepository;
import com.yunxin.admin.system.infra.common.enums.AdminResultCode;
import com.yunxin.admin.system.infra.persistence.entity.SysUserMerchantDO;
import com.yunxin.admin.system.infra.persistence.mapper.SysUserMerchantMapper;
import com.yunxin.common.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author zero°
 * @since 2023-07-11
 */
@Repository
public class UserMerchantRepositoryImpl extends ServiceImpl<SysUserMerchantMapper, SysUserMerchantDO> implements UserMerchantRepository, IService<SysUserMerchantDO> {

    @Override
    public boolean saveUserMerchant(Long userId, List<Long> merchantIds) {
        if (userId == null || CollUtil.isEmpty(merchantIds)) {
            return false;
        }
        if (merchantIds.size() > 1) {
            throw new BusinessException(AdminResultCode.USER_MERCHANT_ERROR);
        }
        // 用户原商户ID集合
        List<Long> userMerchantIds = this.list(new LambdaQueryWrapper<SysUserMerchantDO>()
                        .eq(SysUserMerchantDO::getUserId, userId))
                .stream()
                .map(SysUserMerchantDO::getMerchantId)
                .toList();
        // 新增用户商户
        List<Long> saveMerchantIds;
        if (CollUtil.isEmpty(userMerchantIds)) {
            saveMerchantIds = merchantIds;
        } else {
            saveMerchantIds = merchantIds.stream()
                    .filter(roleId -> !userMerchantIds.contains(roleId)).toList();
        }
        // 用户已存在商户且更新的商户id与历史存在的商户id不一致，则不允许更新(因为系统用户变更商户时,未变更商户账号中的商户id)
        if(CollUtil.isNotEmpty(userMerchantIds) && CollUtil.isNotEmpty(saveMerchantIds)) {
            throw new BusinessException(AdminResultCode.USER_CHANGE_MERCHANT_ERROR);
        }
        List<SysUserMerchantDO> saveUserMerchants = saveMerchantIds.stream().map(merchantId -> new SysUserMerchantDO(userId, merchantId)).toList();
        this.saveBatch(saveUserMerchants);
        // 删除用户商户角色
        if (CollUtil.isNotEmpty(userMerchantIds)) {
            List<Long> removeMerchants = userMerchantIds.stream()
                    .filter(roleId -> !merchantIds.contains(roleId)).toList();
            if (CollUtil.isNotEmpty(removeMerchants)) {
                this.remove(new LambdaQueryWrapper<SysUserMerchantDO>()
                        .eq(SysUserMerchantDO::getUserId, userId)
                        .in(SysUserMerchantDO::getMerchantId, removeMerchants)
                );
            }
        }
        return true;

    }

    @Override
    public List<Long> getUserMerchantIds(Long userId) {
        return this.baseMapper.listMerchantIdsByUserId(userId);
    }

    @Override
    public Long selectMerchantIdByUserId(Long userId) {
        return baseMapper.selectList(new QueryWrapper<SysUserMerchantDO>().eq("user_id",userId)).get(0).getMerchantId();
    }

}
